<?php

declare(strict_types=1);

namespace App\Service;

use Hyperf\Context\ApplicationContext;
use \Hyperf\Filesystem\FilesystemFactory;

class Upload extends BaseService
{
    public function upload($file)
    {
        // 上传驱动
        $drive = 'local';

        $container = ApplicationContext::getContainer();
        // 获取文件工厂实例
        $factory = $container->get(FilesystemFactory::class);

        $extension = $file->getExtension();
        $realName = $file->getClientFilename();
        $dir = 'upload' . '/' . date('Ymd');

        $fileName = date('his') . uniqid() . '.' . $extension;
        $fileSize = $file->getSize();
        $path = $dir . '/' . $fileName;

        // 本地上传
        if ($drive == 'local') {
            $filesystem = $factory->get('local');
            $stream = fopen($file->getRealPath(), 'r+');
            $filesystem->writeStream(
                $path,
                $stream
            );
            fclose($stream);
        }

        return ['name' => $fileName, 'real_name' => $realName, 'path' => $path, 'dir' => $dir, 'url' => $path, 'file_size' => $fileSize];
    }
}
